package com.ingenio.siot.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ingenio.siot.adapter.CriterioAdapter;
import com.ingenio.siot.adapter.EstadoAdapter;
import com.ingenio.siot.adapter.TipoIntervaloAdapter;
import com.ingenio.siot.entity.Criterio;
import com.ingenio.siot.entity.CriterioIntervalo;
import com.ingenio.siot.entity.Estado;
import com.ingenio.siot.entity.TipoIntervalo;

/**
 * Servlet implementation class ABMCriterioServlet
 */
@WebServlet("/ABMCriterio")
public class ABMCriterioServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ABMCriterioServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CriterioAdapter ca = new CriterioAdapter();
		Criterio c = null;
		JSONObject jo = new JSONObject();
		if("eliminar".equals(request.getParameter("type"))){
			try {
				jo.put("action", "eliminar");
				Integer id = Integer.parseInt(request.getParameter("id"));
				if (!ca.devolverCriterio(id).isCriterioPublico()){
			    	ca.eliminarCriterio(id);
			    	jo.put("id", id);
			    	jo.put("error", false);
				}else{
					jo.put("error", true);	// si es el criterio publico no se puede eliminar
				}
			} catch (Exception e) {
				try {
					jo.put("error", true);
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		}else if("editar".equals(request.getParameter("type"))){
			if(true){
				Integer id = Integer.parseInt(request.getParameter("id"));
				try {
					c = ca.devolverCriterio(id);
					String descripcion = request.getParameter("descripcion");
					c.setDescCriterio(descripcion);
					ca.editarCriterio(c);						
					jo.put("action", "editar");
					jo.put("id", c.getIdCriterio());
					jo.put("descripcion", c.getDescCriterio());
					jo.put("error", false);
				} catch (Exception e1) {
					try {
						jo.put("error", true);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					e1.printStackTrace();
				}
			}
		}else if("nuevo".equals(request.getParameter("type"))){
			List<CriterioIntervalo> listaCriteriosIntervalos = new ArrayList<CriterioIntervalo>();
			String descripcion = request.getParameter("descripcion");
			String formula = request.getParameter("formula");
			
			c = new Criterio(descripcion, formula, false);
			String intervalosText = request.getParameter("intervalos");
			CriterioIntervalo ci = null;
			
			TipoIntervaloAdapter tia = new TipoIntervaloAdapter();
			TipoIntervalo ti = null;
			
			EstadoAdapter ea = new EstadoAdapter();
			Estado e = null;
			
			try {
				JSONArray ja = new JSONArray(intervalosText);
				for (int i = 0; i < ja.length(); i++) {
					JSONObject row = (JSONObject)ja.get(i);
					
					Integer idTipoIntervalo = row.getInt("tipo");
					ti = tia.devolverTipoIntervalo(idTipoIntervalo);
					
					Integer idEstado = row.getInt("estado");
					e = ea.devolverEstado(idEstado);
					
					Double max = row.getDouble("max");
					Double min = row.getDouble("min");
					ci = new CriterioIntervalo(ti, null, e, min, max);
					listaCriteriosIntervalos.add(ci);
				}
				c.setIntervalos(listaCriteriosIntervalos);
				
				Integer id = ca.crearCriterio(c);
				
				jo.put("action", "nuevo");
				jo.put("id", id);
				jo.put("descripcion", c.getDescCriterio());
				jo.put("error", false);
				
			} catch (Exception ex) {
				ex.printStackTrace();
			}
					
		}
		response.setContentType("application/json");
		response.getWriter().write(jo.toString());
	}

}
